package yannan.voiplock4ble.service.ble;

import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import yannan.voiplock4ble.MainActivity;
import yannan.voiplock4ble.base.MyApplication;
import yannan.voiplock4ble.bean.ble.BleResponseFactory;
import yannan.voiplock4ble.bean.ble.ConnectLock;
import yannan.voiplock4ble.eventbus.SearchLockBleMsg;
import yannan.voiplock4ble.service.ble.callback.BleCallback;
import yannan.voiplock4ble.eventbus.AddLockEvent;

/**
 * 说明：BLE操作的服务
 * 作者：mainTel
 * 时间：2016/9/5 11:07
 * 备注：
 */
public class BleService extends Service {

    public static final String BLE_MSG_START_SEARCH_TRUE = "ble_msg_start_search";

    BleBinder mBinder = new BleBinder();
    BleCoreService mBleCoreService;
    public List<BluetoothDevice> lockBeanList;
    BleCallback mBleCallback;
    private static BleService bleService;
    boolean isSearching = false;
//    ConnectLock contentLock;

    /**
     * 通过静态方法获取实例  不建议使用这种方法
     *
     * @return
     */
    public static BleService getBleService() {
        return bleService;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        EventBus.getDefault().register(this);
        mBleCoreService = new BleCoreService();
        bleService = this;
        BleUtils.init();
        this.mBleCoreService.setBleCallback(this.mDefaultCallback);
        if (this.mBleCoreService.initialize(this)) {
            lockBeanList = new ArrayList<>();
        }
    }

    /**
     * 开始扫描蓝牙
     * @param msg
     */
    @Subscribe(threadMode = ThreadMode.BACKGROUND)
    public void onEvent(String msg) {
        switch (msg) {
            case BLE_MSG_START_SEARCH_TRUE:
                startSearch();
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.BACKGROUND)
    public void onEvent(SearchLockBleMsg device) {
        if (device.device != null) {
            connectLock(device.device);
        }
    }

    /**
     * 搜索到附近的设备，回调，添加到列表中显示
     */
    BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
        @Override
        public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
            String name = device.getName();
            if (name != null)
                if (name.contains("YN-"))
                    EventBus.getDefault().post(device);
        }
    };

    public void scanAndConnect(String address) {
        mBleCoreService.connect(address);
    }

    /**
     * 搜索附近的设备，
     */
    public void startSearch() {
        final Map<String, BluetoothDevice> map = new HashMap<>();
        if (mBleCoreService.checkBleStatus() && !isSearching) {
            isSearching = true;
            handler.sendEmptyMessageDelayed(STOP_BLE_SCAN, 12000);
            mBleCoreService.mBluetoothAdapter.startLeScan(mLeScanCallback);
        }
    }

    final static int STOP_BLE_SCAN = 100101;

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case STOP_BLE_SCAN:
                    stopScan();
                    break;
            }
        }
    };

    /**
     * 停止搜索附近的设备
     */
    public void stopScan() {
        if (mLeScanCallback != null) {
            isSearching = false;
            mBleCoreService.mBluetoothAdapter.stopLeScan(mLeScanCallback);
            EventBus.getDefault().post(new AddLockEvent(AddLockEvent.MsgWhat.STOP_SEACH_BLE));
        }
    }


    /**
     * 连接设备
     *
     * @param device
     */
    public void connectLock(BluetoothDevice device) {
        if (mBleCoreService.checkBleStatus()) {
            mBleCoreService.connect(device);
        }
    }

    /**
     * 连接设备
     *
     * @param device
     */
    public void connectLock(String device) {
        if (mBleCoreService.checkBleStatus()) {
            mBleCoreService.connect(device);
        }
    }

    /**
     * 关闭连接
     */
    public void disConnect() {
        if (mBleCoreService.checkBleStatus()) {
            mBleCoreService.disconnect();
        }
    }

    /**
     * 发送数据
     *
     * @param order
     */
    public void sendOrder(byte[] order) {
        if (mBleCoreService.checkBleStatus()) {
            mBleCoreService.sendOrder(order);
        } else {
            mDefaultCallback.onSendFinish(-1);
        }
    }


    BleCallback mDefaultCallback = new BleCallback() {
        @Override
        public void onConnectFailed(BluetoothDevice device) { //连接失败
            super.onConnectFailed(device);
        }

        @Override
        public void onConnectTimeout(String paramString) {  //连接超时
            super.onConnectTimeout(paramString);
        }

        @Override
        public void onConnected(BluetoothDevice device) { //连接成功
            super.onConnected(device);
//            new Thread(new Runnable() {
//                @Override
//                public void run() {
//                    try {
//                        Thread.sleep(200); //暂停两百毫秒 然后发送链接命令
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                    }
            if (MyApplication.getInterface().userBean != null)
                sendOrder(BleUtils.connectLock(MyApplication.getInterface().userBean.getUserAccount().getBytes()));
//                }
//            }).start();
        }

        /**
         * 接收到报文
         * @param paramString
         * @param response
         */
        @Override
        public void onDataReceived(String paramString, byte[] response) {
            super.onDataReceived(paramString, response);
            System.out.println("========================="); // 输出
            for (byte b : response) {
                System.out.print(String.format("%02X ", b));
            }
            System.out.println();
            System.out.println("=========================");
            BleResponeUtils.handle(response);
        }

        @Override
        public void onDisconnected(String paramString) {
            super.onDisconnected(paramString);
            Log.d("BleService", "断开连接");
        }

        @Override
        public void onInited(String paramString, boolean paramBoolean) {
            super.onInited(paramString, paramBoolean);
        }

        @Override
        public void onSendFinish(int paramInt) { //发送结果 0成功 -1 失败
        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mBleCoreService != null) {
            mBleCoreService.disconnect();
        }
        EventBus.getDefault().unregister(this);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return this.mBinder;
    }

    public class BleBinder extends Binder {
        public BleBinder() {
        }

        public BleService getService() {
            return BleService.this;
        }
    }

    public void setBleCallback(BleCallback paramBleCallback) {
        this.mBleCallback = paramBleCallback;
    }

}
